<script setup>
import { ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { getCaptchaCode, login } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'


const userStore = useUserStore()
const router = useRouter()


// 表单数据
const formData = ref({
  username: '',
  password: '',
  code: ''
})

const token = ref('')
const setToken = (t) => {
  token.value = t
}

// 验证码相关
const captchaImage = ref('') // base64 图片地址

// 获取验证码方法
const fetchCaptcha = async () => {
  try {
    const res = await getCaptchaCode() // 发起请求
    const { key, imageData } = res.data.data
    userStore.setCaptchaKey(key)
    captchaImage.value = `data:image/png;base64,${imageData}`
  } catch (error) {
    ElMessage.error('获取验证码失败')
    console.error('获取验证码失败:', error)
  }
}

// 页面加载时自动获取验证码
fetchCaptcha()

const handleLogin = async () => {
  const { username, password, code } = formData.value

  if (!username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  if (!password.trim()) {
    ElMessage.warning('请输入密码')
    return
  }

  if (!code.trim()) {
    ElMessage.warning('请输入验证码')
    return
  }

  try {
  const res = await login({
    username,
    password,
    code,
    captchaKey: userStore.captchaKey
  })

  if (res.data.code === 0 && res.data.data.token) {
    ElMessage.success('登录成功')
    userStore.setToken(res.data.data.token)
    setToken(res.data.data.token)
    router.push('/')
  } else {
    ElMessage.error(res.data.msg || '登录失败')
  }
} catch (error) {
  // 只打印错误，不显示提示
  console.error('登录异常:', error)
}
}



</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 增加 label-position 和 label-width -->
      <el-form
        size="large"
        autocomplete="off"
        label-position="right"
        label-width="80px"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="formData.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码"> <!-- 修复为标准写法 -->
          <el-input
            v-model="formData.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <!-- 验证码输入框 -->
        <el-form-item label="验证码">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="formData.code" placeholder="请输入验证码" />
            </el-col>
            <el-col :span="12">
              <img
                v-if="captchaImage"
                :src="captchaImage"
                alt="验证码"
                style="width: 100%; height: 40px; cursor: pointer"
                @click="fetchCaptcha"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .el-form {
      width: 100%;
    }

    .button {
      width: 100%;
    }
  }
}
</style>
